package java.web.java_web_ch08;

import java.sql.*;

/**
 * 订单处理器类
 */
public class OrderProcessor {
    private final Connection  conn;  // 连接对象
    /**
     * 定义带有一个Connection参数的构造方法
     */
    public OrderProcessor(Connection conn) {
        this.conn = conn;
    }
    public void processOrder(int bookId, int userId, int quantity) {
        try {
            conn.setAutoCommit(false);  // 关闭自动提交模式
            double bookPrice = getBookPrice(conn, bookId);  // 获取图书价格
            updateBookStock(conn, bookId, quantity);  // 更新图书库存
            long orderId = createOrder(conn, userId);  // 创建订单
            createOrderItems(conn, orderId, bookId, quantity, bookPrice);  // 创建订单项
            System.out.println("订单已经成功处理。");
            conn.commit();  // 提交事务
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback();  // 事务回滚
                    System.out.println("订单处理失败，事务已回滚。");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);  // 开启自动提交模式
                    conn.close();  // 关闭连接
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private double getBookPrice(Connection conn, int bookId) throws SQLException {
        String sql = "SELECT BookPrice FROM Books WHERE BookID = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, bookId);
            ResultSet resultSet = pstmt.executeQuery();
            if (resultSet.next()) {
                return resultSet.getDouble("BookPrice");
            }
        }
        throw new SQLException("无法找到此ID对应的图书:" + bookId);
    }
    private void updateBookStock(Connection conn, int bookId, int quantity) throws SQLException {
        String sql = "UPDATE Stock SET BookStock = BookStock - ? WHERE BookID = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, quantity);
            pstmt.setInt(2, bookId);
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("库存更新失败，未影响任何行。");
            }
        }
    }
    private long createOrder(Connection conn, int userId) throws SQLException {
        String sql = "INSERT INTO UserOrders (UserID, OrderShippingAddress, OrderShippingCity, OrderShippingZipcode, OrderShippingPhone, OrderPaymentMethod, OrderTotal)\n" +
                "VALUES \n" +
                "(?, '上虞区百官街道新兴路1号', '绍兴', '312300', '13812345678', '支付宝', 108.88)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setInt(1, userId);
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("订单创建失败，未影响任何行。");
            }
            try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    return generatedKeys.getLong(1);
                } else {
                    throw new SQLException("订单创建失败，没有获取到ID。");
                }
            }
        }
    }
    private void createOrderItems(Connection conn, long orderId, int bookId, int quantity, double priceEach) throws SQLException {
        String sql = "INSERT INTO UserOrderItems (OrderID, BookID, Quantity, PriceEach) VALUES (?, ?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, orderId);
            pstmt.setInt(2, bookId);
            pstmt.setInt(3, quantity);
            pstmt.setDouble(4, priceEach);
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("创建订单项失败，未影响任何行。");
            }
        }
    }
    public static void main(String[] args) {
        try {
            Connection conn = DatabaseConnectionPool.getConnection();  // 获取数据库连接
            OrderProcessor orderProcessor = new OrderProcessor(conn);  // 创建OrderProcessor对象
            orderProcessor.processOrder(1, 2, 1);  // 调用processOrder方法处理订单
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}